var SERVER_URL = 'https://api.jushiyunku.com/index.php?m=Hapi';
//var SERVER_URL = 'http://192.168.31.116:8011/index.php?m=Hapi';
var PGYER_APPID = 'ba53a1ce9cb5156a956f240b8e1b92c4';
var STATUSBAR_HEIGHT = 0;

//取消浏览器的所有事件，使得active的样式在手机上正常生效
document.addEventListener('touchstart', function() {
	return false;
}, true);

// 禁止选择
document.oncontextmenu = function() {
	return false;
};

document.onselectstart = function() {
	return false;
};

function plusReady() {
	plus.webview.currentWebview().setStyle({
		scrollIndicator: 'none'
	});

	//计算沉浸式状态栏高度 并调整 header main
	var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);
	if(ms && ms.length >= 3) {
		STATUSBAR_HEIGHT = parseFloat(ms[2]);
	}

}

if(window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
}

(function(w) {
	w.Post = function(url, option, func) {
		mui.ajax(url + "&token=" + getToken(), {
			dataType: 'json',
			type: 'post',
			data: option,
			success: function(data) {
				func(data);
			},
			error: function(xhr, type, errorThrown) {
				try {
					if(typeof(Error) == "function") {
						Error(xhr, type, errorThrown);
					}
				} catch(e) {}
			}
		});
	};
	w.Get = function(url, option, fun) {
		mui.ajax(url + "&token=" + getToken(), {
			dataType: 'json',
			type: 'get',
			data: option,
			success: function(data) {
				fun(data);
			},
			error: function(xhr, type, errorThrown) {
				try {
					if(typeof(Error) == "function") {
						Error(xhr, type, errorThrown);
					}
				} catch(e) {}
			}
		});
	};

	w.clicked = function(url, as, ws) {
		if(mui.os.ios){
			as = as || 'pop-in'
		}else{
			as = as || 'slide-in-right'
		}
			
			ws = ws ||  false
		mui.openWindow({
			url: url,
			id: url,
			createNew: false,
			show: {
				autoShow: true, //页面loaded事件发生后自动显示，默认为true
				aniShow: as, //页面显示动画，默认为”slide-in-right“；
				duration: 300, //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；
			},
			waiting: {
				autoShow: ws, //自动显示等待框，默认为true
				title: '', //等待对话框上显示的提示内容
			}
		})
	}

	w.log = function(data) {
		console.log(JSON.stringify(data));
	}

	w.alertHTML = function(data) {
		alert(JSON.stringify(data));
	}

	/**
	 * 生成随机整数
	 */
	w.RndNum = function(n) {
		var rnd = "";
		for(var i = 0; i < n; i++)
			rnd += Math.floor(Math.random() * 10);
		return rnd;
	};

	//截取url参数
	w.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if(r != null) {
			return unescape(r[2]);
		} else {
			return null;
		}
	}

	w.getUserInfo = function() {
		var userinfo = Smarge.get('userinfo');
		if(userinfo == undefined) {
			return ''
		} else {
			return userinfo;
		}
	}

	w.getUid = function() {
		var userinfo = Smarge.get('userinfo');
		if(userinfo == undefined) {
			return ''
		} else {
			return userinfo.id;
		}
	}

	w.getToken = function() {
		var userinfo = Smarge.get('userinfo');
		if(userinfo == undefined) {
			return ''
		} else {
			return userinfo.token;
		}
	}

	//复制描述
	w.copyToClip = function(text) {
		var _text = text;
		$.toast("已复制到粘贴板", "text");
		switch(plus.os.name) {
			case "Android":
				var Context = plus.android.importClass("android.content.Context");
				var main = plus.android.runtimeMainActivity();
				var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
				plus.android.invoke(clip, "setText", _text);
				break;

			case "iOS":
				var UIPasteboard = plus.ios.importClass("UIPasteboard");
				var generalPasteboard = UIPasteboard.generalPasteboard();
				generalPasteboard.setValueforPasteboardType(_text, "public.utf8-plain-text");
				break;
			default:
				// 其它平台
				break;
		}

	}

	//获取当前时间
	w.getNowFormatDate = function() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if(month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if(strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = year + seperator1 + month + seperator1 + strDate +
			" " + date.getHours() + seperator2 + date.getMinutes() +
			seperator2 + date.getSeconds();
		return currentdate;
	}

	//获取当前时间 并格式化为 20170705
	w.getNowFormatDateDay = function() {
		var date = new Date();
		var seperator1 = "-";
		var seperator2 = ":";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if(month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if(strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = year + '' + month + '' + strDate;
		return currentdate;
	}

	// 对Date的扩展，将 Date 转化为指定格式的String
	// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
	// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
	// 例子： 
	// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
	// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
	w.FormatDate = function(fmt) { //author: meizz 
		var o = {
			"M+": this.getMonth() + 1, //月份 
			"d+": this.getDate(), //日 
			"h+": this.getHours(), //小时 
			"m+": this.getMinutes(), //分 
			"s+": this.getSeconds(), //秒 
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
			"S": this.getMilliseconds() //毫秒 
		};
		if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for(var k in o)
			if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}

	w.nowTime = function() {
		var d = new Date();
		return(d.getTime() / 1000).toFixed(0)
	}

	// 处理返回事件
	w.wsClose = function(hide) {
		//alert('d')
		ws = plus.webview.currentWebview();
		if(hide || ws.preate) {
			ws.hide('auto');
		} else {
			ws.close('auto');
		}
	};

	//关闭指定 id webview
	w.closeWebview = function(id) {
		var ws = plus.webview.getWebviewById(id);
		plus.webview.close(ws);
	}

	w.reGetUserInfo = function() {
		Get(SERVER_URL + '&c=User&a=getInfo', {}, function(data) {
			if(data.status) {
				Smarge.set('userinfo', data.info);
			} else {
				plus.nativeUI.alert(data.info, function() {
					Smarge.set('userinfo', '');
					clicked('login.html')
				}, "提示", "确定");
			}
			//alertHTML(data) 
		})
	}
	//退出登录
	w.logout = function() {
		plus.nativeUI.confirm("你确定要退出登录吗？", function(e) {
			if(e.index == 0) {
				Smarge.set('userinfo', '');
				plus.runtime.restart();
			};
		}, "提示", ["确定", "取消"]);

	}

	//保存图片
	w.SaveImg = function(imgUrl) {
		plus.nativeUI.showWaiting('正在保存')
		var downLoader = plus.downloader.createDownload(imgUrl, {
				"method": 'GET',
				"filename": '_downloads/image/' + md5(imgUrl) + '.jpg',
				"timeout": 10,
				"retry": 2
			},
			function(download, status) {
				//console.log('_downloads/image/' + md5(imgUrl)+'.jpg');
				var fileName = download.filename;
				if(status == 200) {
					plus.gallery.save(fileName, function() {
						setTimeout(function() {
							plus.nativeUI.closeWaiting();
							$.toast('保存成功');
						}, 300)
					}, function() {
						$.toast('保存失败，请重试！', 'text');
					});
				}
			});
		downLoader.start();
	}

	//下载组图 pics为数组
	w.DownloadPics = function(pics) {
		var i = 0;
		var length = pics.length;
		var x = '1/' + length;
		w = plus.nativeUI.showWaiting('下载中 ' + x, {
			width: '120px',
			height: '90px'
		});

		function DownloadImg(imgUrl) {
			var downLoader = plus.downloader.createDownload(imgUrl, {
					"method": 'GET',
					"filename": '_downloads/image/' + md5(imgUrl) + '.jpg',
					"timeout": 10,
					"retry": 2
				},
				function(download, status) {
					var fileName = download.filename;
					if(status == 200) {
						plus.gallery.save(fileName, function() {
							i++;
							if(i < length) {
								DownloadImg(pics[i])
								x = i + '/' + length;
								w.setTitle('下载中 ' + x);
							} else {
								w.close();
								$.toast('下载完成');
							}
						}, function() {
							//mui.toast('保存失败，请重试！');
						});
					}
				});
			downLoader.start();
		}

		DownloadImg(pics[i])
	}

	var shares = null,
		sharewx = null;
	//分享链接
	w.shareLink = function(content, thumbs, href) {
		plus.share.getServices(function(s) {
			shares = s;
			for(var i in s) {
				if('weixin' == s[i].id) {
					sharewx = s[i];
				}
			}
		}, function(e) {
			alert("获取分享服务列表失败：" + e.message);
		});

		plus.nativeUI.actionSheet({
			title: "分享",
			cancel: "取消",
			buttons: [{
				title: "分享给好友"
			}, {
				title: "分享到朋友圈"
			}]
		}, function(e) {
			var index = e.index;
			switch(index) {
				case 0:
					break;
				case 1:
					sharewx.send({
						content: content,
						href: href,
						thumbs: [thumbs + '@!200x200'],
						extra: {
							scene: "WXSceneSession"
						}
					}, function() {
						mui.toast("分享成功！");
					}, function(e) {
						mui.toast("分享失败");
					});
					break;
				case 2:
					sharewx.send({
						content: content,
						href: href,
						thumbs: [thumbs + '@!200x200'],
						extra: {
							scene: "WXSceneTimeline"
						}
					}, function() {
						mui.toast("分享成功！");
					}, function(e) {
						mui.toast("分享失败");
					});
					break;
				default:
					// 其它
					break;
			}
		});

	}

	//一键分享 只支持Android
	w.easyShare = function(pics, brief) {
		if(plus.os.name == 'Android') {

			plus.nativeUI.actionSheet({
				title: "分享",
				cancel: "取消",
				buttons: [{
					title: "朋友圈"
				}, {
					title: "微信好友"
				}]
			}, function(e) {
				var index = e.index;
				switch(index) {
					case 0:
						break;
					case 1:
						wxShare.share('timeLine', pics, brief);
						break;
					case 2:
						wxShare.share('friend', pics, brief);
						break;
					default:
						// 其它
						break;
				}
			});

		}

		if(plus.os.name == 'iOS') {
			mui.alert('iOS系统不支持该功能！')
		}
	}

	// 截取图片后缀用于重命名图片，防止%E5%85%89%E6%98%8E%E8%A1%8C编码的文件不被系统相册识别；
	w.cutImageSuffix = function(imageUrl) {
		var index = imageUrl.lastIndexOf('.');
		return imageUrl.substring(index);
	}

	w.fromToJson = function(form) {
		var result = {};
		var fieldArray = $('#' + form).serializeArray();
		for(var i = 0; i < fieldArray.length; i++) {
			var field = fieldArray[i];
			if(field.name in result) {
				result[field.name] += ',' + field.value;
			} else {
				result[field.name] = field.value;
			}
		}
		return result;
	}

	// 转为unicode 编码  
	w.encodeUnicode = function(str) {
		var res = [];
		for(var i = 0; i < str.length; i++) {
			res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
		}
		return "\\u" + res.join("\\u");
	}

	//RL字符串进行编码
	w.encodeURI = function(sn) {
		return decodeURI("https://sale.jushiyunku.com/h5/Team/share/sn/" + sn)
	}

	//URL传递参数中带有中文转码
	w.getQueryString = function(key) {
		var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
		var result = window.location.search.substr(1).match(reg);
		return result ? decodeURIComponent(result[2]) : null;
	}

	w.Top = function() {
		$(document.body).animate({
			scrollTop: 0
		}, 800);
		$('.main-body').animate({
			scrollTop: 0
		}, 800);
	}

	w.removeDuplicates = function(arr) {
		var temp = {};
		for(var i = 0; i < arr.length; i++)
			temp[arr[i]] = true;
		var r = [];
		for(var k in temp)
			r.push(k);
		return r;
	}

	//验证价格格式
	w.isPriceNumber = function(_keyword) {
		if(_keyword == "0" || _keyword == "0." || _keyword == "0.0" || _keyword == "0.00") {
			_keyword = "0";
			return true;
		} else {
			var index = _keyword.indexOf("0");
			var length = _keyword.length;
			if(index == 0 && length > 1) { /*0开头的数字串*/
				var reg = /^[0]{1}[.]{1}[0-9]{1,2}$/;
				if(!reg.test(_keyword)) {
					return false;
				} else {
					return true;
				}
			} else {
				var reg = /^[1-9]{1}[0-9]{0,10}[.]{0,1}[0-9]{0,2}$/;
				if(!reg.test(_keyword)) {
					return false;
				} else {
					return true;
				}
			}
			return false;
		}
	}

	//升级提示
	w.updateApp = function(type) {

		var _type = type,
			_aId = PGYER_APPID,
			_api_key = '2fb9a5b9631cd0a2ff7a8eca2ccd17c1';

		if(plus.os.name == 'Android') {

			mui.ajax('http://www.pgyer.com/apiv1/app/builds', {
				dataType: 'json',
				type: 'post',
				data: {
					aId: _aId,
					_api_key: _api_key,
					page: 1
				},
				success: function(data) {
					if(data.code == 0) {
						var pgy_version = data.data.list[0].appVersion.replace(/\./g, '');
						var version = plus.runtime.version.replace(/\./g, '');
						if((pgy_version - version) > 0) {
							plus.nativeUI.confirm("发现新版本需要更新吗？", function(e) {
								if(e.index == 0) {
									plus.runtime.openURL('https://www.pgyer.com/apiv1/app/install?aId=' + _aId + '&_api_key=' + _api_key);
								};
							}, "提示", ["确定", "取消"]);
						} else {
							if(_type == 1) {
								alert('已经是最新版本')
							}
						}
					} else {
						mui.alert(data.message)
					}
				}
			});
		}
	}

})(window);